package com.da.javatest.correct;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author chenlida
 * @date 2020/7/4 17:19
 * @description
 */
@RestController
@RequestMapping("/api/correct")
@Slf4j
public class CorrectController {
    /**
     * 计数器
     */
    private static int count = 0;
    /**
     * 错误记录
     */
    private StringBuilder record;
    /**
     * 删除数据线程池资源
     */
    ExecutorService executorService = new ThreadPoolExecutor(20, 30, 0L,
        TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());

    /**
     * 数据处理
     */
    @RequestMapping("/dealData.json")
    public String dealData(String redo, String data) {
        // 这里也可以从其他地方获取数据
        List<String> dataList = Arrays.asList(data.split(","));
        // 存在已经跑过的数据则直接返回
        if (!StringUtils.equals("true", redo)) {
            String result;
            if (dataList.size() == count) {
                result = "订正完成：" + count;
            } else {
                result = "订正中，当前：" + count;
            }
            return result + "\n" + record.toString();
        }

        // 清理缓存后重新开始
        count = 0;
        record = new StringBuilder();

        for (String dataStr : dataList) {
            // 启动线程执行
            executorService.execute(new Thread(() -> {
                try {
                    Result result = fixData(dataStr);
                    if (result.isSuccess()) {
                        String msg = result.getMsg() != null ? result.getMsg() : "成功";
                        record.append(",[").append(dataStr).append("]:" + msg);
                    } else {
                        record.append(",[").append(dataStr).append("]:失败=")
                            .append(result.getMsg());
                    }
                } catch (Exception e) {
                    record.append(",[").append(dataStr).append("]:异常=").append(e.getMessage());
                    log.error("数据处理异常，params={}", dataStr, e);
                } finally {
                    count++;
                }
            }));
        }

        return "订正开始";
    }

    private Result fixData(String dataStr) {
        return null;
    }
}
